package com.yuji.aacar.core.mvvm.appbase;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.yuji.aacar.core.cores.event.CoreEventBusMessage;
import com.yuji.aacar.core.cores.event.CoreEventCenter;
import com.yuji.aacar.core.cores.services.CoreServiceResponse;
import com.yuji.aacar.core.cores.utils.LogUtil;
import com.yuji.aacar.core.mvvm.apptask.TaskManager;
import com.yuji.aacar.core.mvvm.apptask.TaskToken;
import com.yuji.aacar.core.mvvm.apptask.ViewModelManager;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;

/**
 * <li>Package:com.ttp.core.mvvm.appbase</li>
 * <li>Author: lining</li>
 * <li>Date: 2017/3/1</li>
 * <li>Description: Fragment基类</li>
 */

public abstract class CoreBaseFragment extends Fragment implements CoreBaseController {

    public String TAG = this.getClass().getSimpleName();

    /**
     * 基类ViewModel对象
     */
    public CoreBaseViewModel coreBaseViewModel;
    /**
     * 请求的viewModelId
     */
    private String viewModelId;
    /**
     * coreProgressDialog
     */
//    public static CoreProgressDialog coreProgressDialog;
    /**
     * mToast
     */
    private Toast mToast;

    public static Handler coreHandler;

    public View mView;

    /**
     * 接收请求params的对象
     */
    public HashMap<String, Object> requestParams;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        LogUtil.e(this.getClass().getSimpleName(), ViewModelManager.getInstance().getVMInfo());
        prepareModleId();
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        destoryViewModel();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CoreEventCenter.register(this);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        CoreEventCenter.unregister(this);
    }

    //    protected abstract void initViewModel();


    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public void onStop() {
        super.onStop();
    }

    public void prepareModleId() {
        LogUtil.e("--onStart--coreBaseViewModel == null --", coreBaseViewModel == null ? "是空的" : coreBaseViewModel.getClass().getName());
        if (null != coreBaseViewModel) {
            viewModelId = coreBaseViewModel.getViewModelId();
            LogUtil.e("--onStart--coreBaseViewModel == viewModelId --", viewModelId == null ? "没有viewModelId" : viewModelId);
        }
        if (null == coreBaseViewModel) {
            coreBaseViewModel = ViewModelManager.getInstance().viewModelForKey(
                    viewModelId);
            if (null != coreBaseViewModel) {
                LogUtil.e("--onStart--根据viewModelId获得到的coreBaseViewModel--", "[CoreBaseActivity]当前的---coreBaseViewModel---" + coreBaseViewModel.getClass());
                LogUtil.e("--onStart--this--", this.getClass().getSimpleName());
                coreBaseViewModel.setActivity(this.getActivity());
                coreBaseViewModel.setFragment(this);
                alreadyBindBaseViewModel();
                if (coreBaseViewModel.getResponse() != null) {
                    if (coreBaseViewModel.isDataReady.get()
                            && !coreBaseViewModel.isRefreshed.get()) {
                        requestSuccess(coreBaseViewModel.getResponse());
                    } else if (coreBaseViewModel.isFailed.get()) {
                        LogUtil.e("activity", "[" + this.getClass().getSimpleName() + "]" + "[onStart]: coreBaseViewModel.isFailed");
                        coreBaseViewModel
                                .requestFailed(coreBaseViewModel.getResponse());
                    } else {
                        coreBaseViewModel.requestFailed(coreBaseViewModel.getResponse());
                    }
                } else {
                    LogUtil.e("activity", "[" + this.getClass().getSimpleName() + "]" + "[onStart]: coreBaseViewModel.getResponse() == null");
                }
            } else {
                LogUtil.e("activity", this.getClass().getSimpleName() + "[onStart][baseviewmodel]:" + viewModelId + " is null");
                coreBaseViewModel = ViewModelManager.getInstance().newViewModel(this.getClass().getName());
                coreBaseViewModel.showProgressBar = false;
                coreBaseViewModel.setActivity(this.getActivity());
                coreBaseViewModel.setFragment(this);
                viewModelId = coreBaseViewModel.getViewModelId();
                alreadyBindBaseViewModel();
                LogUtil.d("fragment--", "create new viewModel:[" + viewModelId + "]");
            }
        } else {
            LogUtil.e("fragment", "[" + this.getClass().getSimpleName() + "]" + "[onStart]: coreBaseViewModel is NOT null (should be null)");
            LogUtil.e("fragment--", this.getClass().getSimpleName() + viewModelId);
            LogUtil.e("fragment--", this.getClass().getSimpleName() + "[onStart][coreBaseViewModel]:" + coreBaseViewModel.getClass());
        }
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (coreBaseViewModel != null) {
            coreBaseViewModel.isRefreshed.set(false);
        }
    }

    /**
     * activity已经绑定了viewmodel，可以直接调用baseviewmodel获取viewmodel
     */
    public void alreadyBindBaseViewModel() {
        //        if (coreBaseViewModel.getTaskToken() != null) {
        //            requestTokens.add(coreBaseViewModel.getTaskToken());
        //        }
    }

    public void destoryViewModel() {
        LogUtil.e(this.getClass().getSimpleName(), "destoryViewModel() is called!!!");
        if (coreBaseViewModel != null) {
            LogUtil.e("--destoryViewModel--", coreBaseViewModel);
            TaskManager.getInstance().cancelTask(coreBaseViewModel.getTaskToken());
        }
        coreBaseViewModel = null;
        ViewModelManager.getInstance().destoryViewModel(viewModelId);
    }


    public String getViewModelId() {
        return viewModelId;
    }

    @Override
    public CoreBaseViewModel getViewModel() {
        return coreBaseViewModel;
    }

    @Override
    public void setViewModel(CoreBaseViewModel viewModel) {
        coreBaseViewModel = viewModel;
    }


    /**
     * 加载progressView
     */
    public void showProgress() {
        //        startProgressDialog(false);
    }

    /**
     * 取消ProgressView
     *
     * @param
     */
    public void dismissProgress() {
//        if (coreProgressDialog != null) {
//            coreProgressDialog.dismiss();
//        }
    }

    public void showToast(String text) {
        this.showToast(text, Toast.LENGTH_SHORT);
    }

    public void showToast(String text, int duration) {
        if (mToast != null) {
            mToast.cancel();
            mToast = null;
        }
        mToast = Toast.makeText(getActivity(), text, duration);
        mToast.setGravity(Gravity.CENTER, 0, 0);
        mToast.show();
    }

    public void cancelToast() {
        if (mToast != null) {
            mToast.cancel();
        }
    }


    /*********
     * 网络请求
     * @param method
     */
    public void doTask(String method) {
        TaskManager.getInstance().doTask(coreBaseViewModel, method, requestParams);
    }

    /*********
     * 网络请求
     * @param methodName
     */
    public void doTask(String methodName, HashMap<String, Object> params) {
        TaskManager.getInstance().doTask(coreBaseViewModel, methodName, params);
    }

    /**
     * 取消一个网络请求,需要传入dotask时候返回的唯一令牌
     *
     * @param token 线程对象
     */
    public void cancelTask(TaskToken token) {
        TaskManager.getInstance().cancelTask(token);
    }

    @Override
    public void requestSuccess(CoreServiceResponse response) {
        LogUtil.e("===requestSuccess===", this);
    }

    @Override
    public void requestFailed(CoreServiceResponse response) {

    }


    @Subscribe
    public void onEventBusMessage(CoreEventBusMessage message) {
        handleMessage(message);
        if (message.getMessageCode().contentEquals(String.valueOf(CoreEventCenter.BUSSINESS_SERVICE_ERROR))) {
            TaskToken token = new TaskToken();
            token.methodName = message.getMethodName();
            token.requestCode = message.getRequestCode();
            CoreServiceResponse response = new CoreServiceResponse();
            response.setRequestCode(message.getRequestCode());
            response.setTokenObj(token);
            response.setMessage(message.getMessage());
            response.setResultCode(CoreEventCenter.BUSSINESS_SERVICE_ERROR);
            requestFailed(response);
        } else if (message.getMessageCode().contentEquals(String.valueOf(CoreEventCenter.NETWOR_NOT_CONNECT))) {
            TaskToken token = new TaskToken();
            token.methodName = message.getMethodName();
            token.requestCode = message.getRequestCode();
            CoreServiceResponse response = new CoreServiceResponse();
            response.setRequestCode(message.getRequestCode());
            response.setTokenObj(token);
            response.setMessage(message.getMessage());
            response.setResultCode(CoreEventCenter.NETWOR_NOT_CONNECT);
            requestFailed(response);
        }
    }

    public void handleMessage(CoreEventBusMessage message) {

    }
}
